package com.taptech.doufu.ui.activity

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.content.ContextCompat
import android.view.View
import android.view.animation.Animation
import android.widget.RelativeLayout
import androidx.recyclerview.widget.LinearLayoutManager
import com.taptech.doufu.R
import com.taptech.doufu.app.WeMediaApplication
import com.taptech.doufu.constant.Constant
import com.taptech.doufu.constant.ShareType
import com.taptech.doufu.constant.UmengEventName
import com.taptech.doufu.constant.UserDetailCardType
import com.taptech.doufu.model.user.*
import com.taptech.doufu.presenter.user.IUserDetailView
import com.taptech.doufu.presenter.user.UserDetailPresenter
import com.taptech.doufu.services.personalcenter.AccountService
import com.taptech.doufu.ui.activity.base.BaseMvpActivity
import com.taptech.doufu.ui.activity.weex.SimpleWeexActivity
import com.taptech.doufu.ui.activity.weex.StartWeexActivityUtils
import com.taptech.doufu.ui.adapter.UserDetailAdapter
import com.taptech.doufu.ui.dialog.DoubleBtnTiptDialog
import com.taptech.doufu.util.*
import com.taptech.doufu.weex.notification.QLXNotificationCenter
import kotlinx.android.synthetic.main.activity_user_detail.*
import kotlinx.android.synthetic.main.view_user_detail_title_bar.*
import kotlinx.android.synthetic.main.view_user_detail_title_bar_2.*

class UserDetailActivity : BaseMvpActivity<UserDetailPresenter>(),IUserDetailView {



    override fun initPresenter(intent: Intent) {
        mPresenter = UserDetailPresenter(this, this,intent)
        mPresenter.getUserDetail()

    }

    override fun initView() {
        setStatusBarFullTransparent()
        val titleBarHeight = if (Build.VERSION.SDK_INT >= 21) ScreenUtil.dip2px(this, 44f)+ ScreenUtil.getStatusHeight(this) else ScreenUtil.dip2px(this, 44f)
        val titleBarParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, titleBarHeight)
        layTitleBar.layoutParams = titleBarParams
        layTitleBar2.layoutParams = titleBarParams
        layBack.setOnClickListener { finish() }
        layBack2.setOnClickListener { finish() }

        svContent.setOnScrollChangeListener { _, scrollY, _, _ ->
            if (scrollY < 300) {
                val alpha = 1f/300f * scrollY
                layTitleBar2.alpha = alpha
                layTitleBar.alpha = 1f - alpha
            }else{
                layTitleBar.alpha = 0f
                layTitleBar2.alpha = 1f
            }
        }
        tvAttention.setOnClickListener {
            if (!AccountService.getInstance().checkAndLogin()) {
                return@setOnClickListener
            }
            if (mPresenter.hasAttention) {
                toastAttentionTipDialog()
            }else{
                tvAttention.text = "关注..."
                mPresenter.attentionUser()
            }
        }
        QLXNotificationCenter.getInstance().addNotify("kTFUserDidLoginCompleteNotification", this) { _, _ ->
            setBottomLayout(mPresenter.uid,mPresenter.hasAttention)
        }
        ivUserHead.setOnClickListener {
            if (AccountService.getInstance().isLogin && AccountService.getInstance().userUid.toInt() == mPresenter.uid) {
                SimpleWeexActivity.startActivity(this@UserDetailActivity,"vue/login/TFUserInfoEditPage.js")
            }
        }
        tvEditInfo.setOnClickListener {
            if (AccountService.getInstance().isLogin && AccountService.getInstance().userUid.toInt() == mPresenter.uid) {
                SimpleWeexActivity.startActivity(this@UserDetailActivity,"vue/login/TFUserInfoEditPage.js")
            }
        }
        tvSendMsg.setOnClickListener {
            if (Constant.managerIdSet.contains(mPresenter.uid.toString())) {
                val intent = Intent(this@UserDetailActivity, BrowseActivity::class.java)
                intent.putExtra(Constant.URL, "http://api.doufu.la/index.php/help/question")
                intent.putExtra(Constant.TITLE, "")
                startActivity(intent)
            } else {
                StartWeexActivityUtils.startPrivateMsgActivity(this, mPresenter.uid.toString(),
                        mPresenter.nickname)
            }
        }

        layShare.setOnClickListener {
            gotoShare()
//            shareSystemDialog()
        }

        layShare2.setOnClickListener {
            gotoShare()
//            shareSystemDialog()
        }

    }

    override fun getLayout(): Int {
        return R.layout.activity_user_detail
    }


    private fun setPosterTipAnimation() {

        val animationAlphaStart = ObjectAnimator.ofFloat(ivPostTip,"alpha",0f,1f)
        animationAlphaStart.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator?) {
                super.onAnimationEnd(animation)
                val animationEnd = ObjectAnimator.ofFloat(ivPostTip,"alpha",1f,0f)
                animationEnd.duration = 500
                animationEnd.startDelay = 3000
                animationEnd.start()
            }
        })
        val animationScaleX = ObjectAnimator.ofFloat(ivPostTip,"scaleX",0f,1f)
        val animationScaleY = ObjectAnimator.ofFloat(ivPostTip,"scaleY",0f,1f)
        ivPostTip.pivotX = ScreenUtil.dip2px(this,38f).toFloat()
        ivPostTip.pivotY = 0f
        val animationSet = AnimatorSet()
        animationSet.duration = 500
        animationSet.startDelay = 1000
        animationSet.play(animationAlphaStart).with(animationScaleX).with(animationScaleY)
        animationSet.start()
    }


    override fun getUserDetailResult(detail: UserDetailBean) {
        setUserInfo(detail.userInfo,detail.expInfo)
        if (isSomeContentHidden(detail.list, detail.is_author)) {
            layHidden.visibility = View.VISIBLE
        }else{
            layHidden.visibility = View.GONE
        }
        setContent(detail.list,detail.readRecordStatus)
        setBottomLayout(detail.userInfo.uid,detail.following>0)
        val params = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
        params.addRule(RelativeLayout.CENTER_VERTICAL)
        if (detail.is_author > 0) {
            layShare.visibility = View.VISIBLE
            layShare2.visibility = View.VISIBLE
            params.addRule(RelativeLayout.LEFT_OF,R.id.layShare)
            setPosterTipAnimation()
        }else{
            layShare.visibility = View.GONE
            layShare2.visibility = View.GONE
            params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
            params.rightMargin = ScreenUtil.dip2px(this,20f)
        }
        tvEditInfo.layoutParams = params
    }

    private fun shareSystemDialog() {
        val shareBean = mPresenter.shareInfo
        val desc = "我正在 豆花 App 看" + mPresenter.nickname + " 的小说，99%女生都在用的耽美言情BL同人小说阅读器，邀请你跟我一起看!!! " + shareBean.url
        ShareUtil.shareText(this, mPresenter.nickname, desc)
    }

    private fun gotoShare() {
        val dialog = ShareUtils.getBottomDialog(this,false,object :ShareUtils.OnClickListener{
            override fun onClickHelp() {
                BrowseActivity.startActivity(this@UserDetailActivity,"https://api.doufu.la/journal/detail?id=640")
            }

            override fun onClickItem(social_type: Int) {
                val map = HashMap<String, String>()
                map["type"] = "$social_type"
                TMAnalysis.event(this@UserDetailActivity, UmengEventName.USER_DETAIL_SHARE_ACTION, map)
                when (social_type) {
                    ShareType.Poster -> UserPosterActivity.startActivity(this@UserDetailActivity,mPresenter.uid)
                    ShareType.CopyLink -> ShareUtils.copyLike(this@UserDetailActivity,mPresenter.shareInfo.url)
                    else -> {
                        val shareBean = mPresenter.getShareBean(social_type)
                        shareBean.social_type = social_type
                        ShareUtils.thirdPartyShare(this@UserDetailActivity,shareBean)
                    }
                }
            }
        })
        dialog.show()
    }

    private fun setBottomLayout(uid: Int,hasAttention: Boolean) {
        if (AccountService.getInstance().isLogin && AccountService.getInstance().userUid.toInt() == uid) {
            layBottom.visibility = View.GONE
        }else{
            layBottom.visibility = View.VISIBLE
            setAttention(hasAttention)
        }
    }

    private fun setUserInfo(userInfo: UserInfo,expInfo: ExpInfo) {
        if (AccountService.getInstance().isLogin && AccountService.getInstance().userUid.toInt() == userInfo.uid){
//            tvEditInfo.visibility = View.VISIBLE
        }else{
            tvEditInfo.visibility = View.GONE
        }
        tvUserName.text = userInfo.nickname
        tvTopTitle.text = userInfo.nickname
        tvUserSignature.text = userInfo.user_signature
        GlideUtil.displayCircleImage(ivUserHead,userInfo.head_image)
        if (expInfo.level > 0) {
            tvLevel.text = "豆花 Lv.${expInfo.level}"
            GlideUtil.displayImage(ivLevel, expInfo.level_icon)
            tvLevel.visibility = View.VISIBLE
            ivLevel.visibility = View.VISIBLE
        } else {
            tvLevel.visibility = View.GONE
            ivLevel.visibility = View.GONE
        }
        tvVip.visibility = View.VISIBLE
        ivVip.visibility = View.VISIBLE
        when {
            expInfo.is_year_vip > 0 -> {
                ivVip.setImageResource(R.drawable.icon_year_vip)
                tvVip.text = "年度会员"
            }
            expInfo.is_vip > 0 -> {
                ivVip.setImageResource(R.drawable.icon_normal_vip)
                tvVip.text = "会员"
            }
            else -> {
                tvVip.visibility = View.GONE
                ivVip.visibility = View.GONE
            }
        }

    }

    override fun getUserNovelList(list: MutableList<NovelBean>) {

    }

    private fun setContent(list: MutableList<ListItem>,readRecordStatus:Int) {
        val adapter = UserDetailAdapter(this,mPresenter.uid,readRecordStatus)
        adapter.setData(list)
        val manager = object : LinearLayoutManager(this){
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        mRecyclerView.layoutManager = manager
        mRecyclerView.adapter = adapter
    }

    private fun isSomeContentHidden(list: MutableList<ListItem>,isAuthor:Int):Boolean{
        //如果是自己内容没有隐藏
        if (AccountService.getInstance().isLogin && AccountService.getInstance().userUid.toInt() == mPresenter.uid){
            return false
        }
        var count = 0
        if (isAuthor > 0) {
            for (item in list) {
                if (item.type == UserDetailCardType.LATEST_ACTIVITIES ||
                        item.type == UserDetailCardType.LATEST_REVIEW ||
                        item.type == UserDetailCardType.LATEST_JOURNAL) {
                    count++
                }
            }
            return count < 3
        }else{
            for (item in list) {
                if (item.type == UserDetailCardType.LATEST_ACTIVITIES ||
                        item.type == UserDetailCardType.LATEST_REVIEW ||
                        item.type == UserDetailCardType.LATEST_JOURNAL||
                        item.type == UserDetailCardType.LATEST_READ) {
                    count++
                }
            }
            return count < 4
        }

    }


    private fun toastAttentionTipDialog() {
        val dialog = DoubleBtnTiptDialog(this,R.style.updateDialog,"是否取消关注", "确定",DoubleBtnTiptDialog.CallBack {
            tvAttention.text = "取消关注..."
            mPresenter.attentionUser()
        })
        dialog.show()
    }

    private fun setAttention(hasAttention: Boolean) {
        if (hasAttention) {
            tvAttention.text = "已关注"
            if (WeMediaApplication.getInstance().isDayNightMode_Night) {
                tvAttention.setBackgroundResource(R.drawable.biankuang_red_coner_dark)
                tvAttention.setTextColor(ContextCompat.getColor(this,R.color.theme_main_dark))
            }else{
                tvAttention.setBackgroundResource(R.drawable.biankuang_red_coner)
                tvAttention.setTextColor(ContextCompat.getColor(this,R.color.text_color_57))
            }
        }else{
            tvAttention.text = "关注"
            if (WeMediaApplication.getInstance().isDayNightMode_Night) {
                tvAttention.setBackgroundResource(R.drawable.cycle_red_night)
                tvAttention.setTextColor(ContextCompat.getColor(this,R.color.text_dark))
            }else{
                tvAttention.setBackgroundResource(R.drawable.cycle_red)
                tvAttention.setTextColor(ContextCompat.getColor(this,R.color.text_color_42))
            }
        }
    }

    override fun attentionUser(cancel: Boolean, success: Boolean) {
        if (cancel) {
            //取消关注
            if (success){
                setAttention(false)
            }else{
                setAttention(true)
            }
        }else{
            if (success) {
                setAttention(true)
            }else{
                setAttention(false)
            }
        }
    }



    companion object{
        const val INTENT_KEY_UID = "intent_key_uid"
        fun startActivity(context:Context,uid:Int) {
            val intent = Intent(context, UserDetailActivity::class.java)
            intent.putExtra(INTENT_KEY_UID, uid)
            context.startActivity(intent)
        }

        fun startActivity(context:Context,uid:Int,flag:Int) {
            val intent = Intent(context, UserDetailActivity::class.java)
            intent.putExtra(INTENT_KEY_UID, uid)
            intent.flags = flag
            context.startActivity(intent)
        }

        fun startActivity(context: Context, uid: String) {
            val intent = Intent(context, UserDetailActivity::class.java)
            intent.putExtra(INTENT_KEY_UID, uid.toInt())
            context.startActivity(intent)
        }

        fun startActivity(context: Context, uid: String,flag: Int) {
            val intent = Intent(context, UserDetailActivity::class.java)
            intent.putExtra(INTENT_KEY_UID, uid.toInt())
            intent.flags = flag
            context.startActivity(intent)
        }

    }
}